package com.linktel.productionLine.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.linktel.productionLine.EasyExcel.CommentCellWriteHandler;
import com.linktel.productionLine.EasyExcel.monthPlanning.MonthlyPlanningListener;
import com.linktel.productionLine.EasyExcel.monthPlanning.model.WriteMonthlyPlanning;
import com.linktel.productionLine.EasyExcel.util.Methods;
import com.linktel.productionLine.common.BaseContext;
import com.linktel.productionLine.common.BaseResponse;
import com.linktel.productionLine.common.ErrorCode;
import com.linktel.productionLine.common.ResultUtils;
import com.linktel.productionLine.dao.BaseStepDao;
import com.linktel.productionLine.dao.MonthlyPlanningDao;
import com.linktel.productionLine.dao.ProductionLineDao;
import com.linktel.productionLine.entity.dto.monthlyPlanning.MonthlyPlanningKeyProcessDTO;
import com.linktel.productionLine.entity.dto.monthlyPlanning.MonthlyPlanningNumberDTO;
import com.linktel.productionLine.entity.query.monthlyPlanning.*;
import com.linktel.productionLine.exception.BusinessException;
import com.linktel.productionLine.service.MonthlyPanningService;
import lombok.AllArgsConstructor;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * 对产线月度规划产能信息的有关请求
 *
 * @Author HuangJiaHui
 * @Date 2023/8/25 9:35
 */
@RestController
@RequestMapping("/monthly-planning")
@AllArgsConstructor
public class MonthlyPlanningController {
    private MonthlyPanningService monthlyPanningService;
    private MonthlyPlanningDao monthlyPlanningDao;
    private BaseStepDao baseStepDao;
    private ProductionLineDao productionLineDao;
    /**
     * 根据用户id，查询对应产线月度规划产能信息（总览，不包括关键工序）
     *
     * @param commitUserId 用户id
     * @return 产线月度规划产能信息列表
     */
    @GetMapping("/number")
    public BaseResponse<List<MonthlyPlanningNumberDTO>> listMonthlyPlanningNumberDTO(Long commitUserId) {
        if (commitUserId == null || commitUserId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<MonthlyPlanningNumberDTO> monthlyCapacityInfoDTOList = monthlyPanningService.listMonthlyPlanningNumberDTO(commitUserId);
        return ResultUtils.success(monthlyCapacityInfoDTOList);
    }
    /**
     * 新增产线月度规划产能信息（总览，不包括关键工序）
     *
     * @param addMonthlyPlanningNumberQuery 新增的产线月度规划产能信息
     * @return 是否新增成功
     */
    @PostMapping("/number")
    public BaseResponse<Boolean> addMonthlyPlanningNumber(@RequestBody AddMonthlyPlanningNumberQuery addMonthlyPlanningNumberQuery) {
        if (addMonthlyPlanningNumberQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Boolean result = monthlyPanningService.addMonthlyPlanningNumber(addMonthlyPlanningNumberQuery);
        return ResultUtils.success(result);
    }

    /**
     * 修改产线月度规划产能信息（总览，不包括关键工序），只允许修改产能
     *
     * @param editMonthlyPlanningNumberQuery 修改的产线月度规划产能信息
     * @return 是否修改成功
     */
    @PutMapping("/number")
    public BaseResponse<Boolean> editMonthlyPlanningNumber(@RequestBody EditMonthlyPlanningNumberQuery editMonthlyPlanningNumberQuery) {
        if (editMonthlyPlanningNumberQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Boolean result = monthlyPanningService.editMonthlyPlanningNumber(editMonthlyPlanningNumberQuery);
        return ResultUtils.success(result);
    }

    /**
     * 删除产线月度规划产能信息（总览，不包括关键工序）
     *
     * @param deleteMonthlyPlanningNumberQuery 删除的产线月度规划产能信息（总览，不包括关键工序）
     * @return 是否删除成功
     */
    @DeleteMapping("/number")
    public BaseResponse<Boolean> deleteMonthlyPlanningNumber(@RequestBody DeleteMonthlyPlanningNumberQuery deleteMonthlyPlanningNumberQuery) {
        if (deleteMonthlyPlanningNumberQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Boolean result = monthlyPanningService.deleteMonthlyPlanningNumber(deleteMonthlyPlanningNumberQuery);
        return ResultUtils.success(result);
    }

    /**
     * 根据登录用户id、产线id，年、月查询所有关键工序信息
     *
     * @param listMonthlyPlanningKeyProcessQuery 请求封装
     * @return 产线月度规划产能信息列表
     */
    @GetMapping("/key-process")
    public BaseResponse<List<MonthlyPlanningKeyProcessDTO>> listMonthlyPlanningKeyProcessDTO(ListMonthlyPlanningKeyProcessQuery listMonthlyPlanningKeyProcessQuery) {
        if (listMonthlyPlanningKeyProcessQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<MonthlyPlanningKeyProcessDTO> monthlyPlanningKeyProcessDTOList = monthlyPanningService.listMonthlyPlanningKeyProcessDTO(listMonthlyPlanningKeyProcessQuery);
        return ResultUtils.success(monthlyPlanningKeyProcessDTOList);
    }

    /**
     * 新增产线月度规划关键工序信息
     *
     * @param addMonthlyPlanningKeyProcessQuery 新增的产线月度规划关键工序信息封装
     * @return 是否新增成功
     */
    @PostMapping("/key-process")
    public BaseResponse<Boolean> addMonthlyPlanningKeyProcess(@RequestBody AddMonthlyPlanningKeyProcessQuery addMonthlyPlanningKeyProcessQuery) {
        if (addMonthlyPlanningKeyProcessQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Boolean result = monthlyPanningService.addMonthlyPlanningKeyProcess(addMonthlyPlanningKeyProcessQuery);
        return ResultUtils.success(result);
    }

    /**
     * 修改产线月度规划关键工序信息
     *
     * @param editMonthlyPlanningKeyProcessQuery 修改的产线月度规划关键工序信息封装
     * @return 是否修改成功
     */
    @PutMapping("/key-process")
    public BaseResponse<Boolean> editMonthlyPlanningKeyProcess(@RequestBody EditMonthlyPlanningKeyProcessQuery editMonthlyPlanningKeyProcessQuery) {
        if (editMonthlyPlanningKeyProcessQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Boolean result = monthlyPanningService.editMonthlyPlanningKeyProcess(editMonthlyPlanningKeyProcessQuery);
        return ResultUtils.success(result);
    }

    /**
     * 删除产线月度规划关键工序信息
     *
     * @param deleteMonthlyPlanningKeyProcessQuery 删除的产线月度规划关键工序信息封装
     * @return 是否删除成功
     */
    @DeleteMapping("/key-process")
    public BaseResponse<Boolean> deleteMonthlyPlanningKeyProcess(@RequestBody DeleteMonthlyPlanningKeyProcessQuery deleteMonthlyPlanningKeyProcessQuery) {
        if (deleteMonthlyPlanningKeyProcessQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Boolean result = monthlyPanningService.deleteMonthlyPlanningKeyProcess(deleteMonthlyPlanningKeyProcessQuery);
        return ResultUtils.success(result);
    }

    /**
     * 下载excel文件，内容包括筛选查询后的全部数据
     *
     * @param commitUserId 当前登录用户id
     */
    @GetMapping("/download")
    public void downloadMonthlyPlanningData(Long commitUserId, HttpServletResponse response) {
        if (commitUserId == null || commitUserId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<WriteMonthlyPlanning> writeMonthlyPlanning = monthlyPanningService.downloadAttendanceDate(commitUserId);
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 防止中文乱码
            String fileName = URLEncoder.encode("月度产能规划信息", "UTF-8")
                    .replaceAll("\\+","%20");
            response.setHeader("Content-disposition", "attachment;filename*=UTF-8''" + fileName + ExcelTypeEnum.XLSX.getValue());
            //响应的输入流
            ServletOutputStream outputStream = response.getOutputStream();
            // workbook
            ExcelWriterBuilder writeWorkBook = EasyExcel.write(outputStream, WriteMonthlyPlanning.class).inMemory(Boolean.TRUE)
                    .head(WriteMonthlyPlanning.class)
                    .useDefaultStyle(false)
                    .registerWriteHandler(new CommentCellWriteHandler(Methods.getNotationMap(WriteMonthlyPlanning.class)));// 添加备注的监听器

            // sheet
            writeWorkBook.sheet().sheetName("月度产能规划信息").sheetNo(0).doWrite(writeMonthlyPlanning);
            outputStream.flush();
            outputStream.close();


        }catch (IOException | IllegalArgumentException e){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "导出失败");
        }
    }
    /**
     * 上传excel文件，批量保存月度规划产能信息
     *
     * @param file excel文件
     * @param currentUserId 当前用户Id
     * @return 是否插入成功
     */
    @PostMapping("/upload")
    public BaseResponse<String> upload(@Param("file") MultipartFile file, Long currentUserId) {
        if (file == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "上传数据为空");
        }
        try {
            EasyExcel.read(file.getInputStream(), WriteMonthlyPlanning.class, new MonthlyPlanningListener(monthlyPlanningDao, currentUserId, productionLineDao, baseStepDao)).excelType(ExcelTypeEnum.XLSX).sheet().doRead();
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        String currentLog = BaseContext.getCurrentLog();
        return ResultUtils.success(currentLog);
    }
}
